﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using UnityTemplate.API.LogHelper;
using UnityTemplate.ApiModel;

namespace UnityTemplate.API.Filter
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly IHostEnvironment _env;
        private readonly ILoggerHelper _loggerHelper;

        public GlobalExceptionFilter(IHostEnvironment env, ILoggerHelper loggerHelper)
        {
            _env = env;
            _loggerHelper = loggerHelper;
        }

        public void OnException(ExceptionContext context)
        {
            context.Result = new InternalServerErrorObjectResult(BaseResponse.BadRequest(context.Exception.Message, StatusCodes.Status500InternalServerError));

            //采用log4net 进行错误日志记录
            _loggerHelper.Error(typeof(GlobalExceptionFilter), context.Exception.Message, context.Exception);

        }
        public class InternalServerErrorObjectResult : ObjectResult
        {
            public InternalServerErrorObjectResult(object value) : base(value)
            {
                StatusCode = StatusCodes.Status500InternalServerError;
            }
        }
    }
}
